<template>
  <div style="padding:30px;">
    <el-form :inline="true" :model="form" class="demo-form-inline">
      <el-form-item label="商品名称">
        <el-input v-model="form.name" clearable placeholder="商品名称"></el-input>
      </el-form-item>
      <el-form-item label="商品状态">
         <el-select v-model="form.state" clearable placeholder="请选择">
              <el-option label="上架" value="1"></el-option>
              <el-option label="下架" value="0"></el-option>
         </el-select>
      </el-form-item>
      <el-form-item label="商品类别">
    <!-- <el-select v-model="form.typeId" clearable placeholder="请选择商品类别">
          <el-option v-for="item in showType" :key="item.id" :value="item.id" :label="item.name"/>
     </el-select> -->
     <!-- filterable:意思是可搜索  可以快速查找存在的类别
          clearable: 清空当前所选
          :show-all-levels="false" :show-all-levels定义是否显示完整的路径，
                                    将其赋值为false则仅显示最后一级 -->
      <el-cascader
           :props="{value:'id',label:'name',children:'children'}"
           :options="showType"
           v-model="form.typeId"
           :value-key="form.typeId"
           :value="showType.id"
           :key="showType.id"
           :clearable="true"
           :show-all-levels="false"
           filterable
           clearable
           @change="handleChange"></el-cascader>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="onSubmit">查询</el-button>
      </el-form-item>
    </el-form>
          <!-- <el-col :span="3"> -->
            <el-button plain size="small" icon="el-icon-plus" type="primary"
                @click="adds()">新增商品</el-button>
            <el-button plain size="small" icon="el-icon-edit" type="success"
                @click="updatePrice()">快速改价</el-button>
            <el-button
                 plain
                 size="small"
                 icon="el-icon-delete"
                 type="danger"
                @click="batchList()"
                :disabled="batchDeleteArr.length === 0">批量删除</el-button></br></br>
          <el-table ref="filterTable"
              :data="tableData"
              @selection-change="handleSelectionChange"
                  border
                  stripe
              style="width: 100%">
            <el-table-column type="selection" width="55"></el-table-column><!-- 复选框 -->
            <el-table-column prop="num" label="序号" width="180"></el-table-column>
            <el-table-column prop="name" label="商品名称" width="180"></el-table-column>
            <el-table-column prop="typeName" label="商品类别" width="180"></el-table-column>
            <el-table-column prop="shou" label="零售价" width="180"> </el-table-column>
            <el-table-column prop="standby3" label="最低售价" width="180"> </el-table-column>
            <el-table-column prop="jin" label="进货价" width="180"> </el-table-column>
            <el-table-column prop="danWei" label="商品单位" width="180"></el-table-column>
            <el-table-column prop="remark" label="商品备注" width="180"></el-table-column>
            <el-table-column prop="state" label="状态" width="width: 20%">
              <template slot-scope="scope">
                <el-tag :type="scope.row.state == '0' ? 'danger' : 'primary'" disable-transitions>
                {{scope.row.state==0?'下架':'上架'}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" align="center" width="120px">
              <template slot-scope="scope">
                <el-button type="text" icon="el-icon-edit"
                    @click="updateProduct(scope.row)" size="small">编辑</el-button>
                <el-button type="text" icon="el-icon-delete"
                    @click="delProduct(scope.row)" size="small">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="block">
            <!-- <el-tag class="demonstration">调整每页显示条数</el-tag> -->
            <el-pagination
             background layout="sizes,prev, pager, next"
             :total="count"
             :page-sizes="[6, 7, 8, 9]"
             :page-size="6"
               @current-change="showByLimit"
               @size-change="handleSizeChange">
            </el-pagination>
          </div>


    <!--添加 -->
    <el-dialog
         title="新增商品"
         v-dialogDrag
         :close-on-click-modal="false"
         :modal="false"
         :visible.sync="addshow">
         <!-- :inline="true" class="demo-form-inline":将一列改为横向流式排布 -->
    <el-form :model="addform" :inline="true" class="demo-form-inline" :rules="rules" ref="addform" label-width="120px">
          <el-form-item label="商品序号" prop="num">
            <el-input v-model="addform.num" clearable placeholder="商品序号"></el-input>
          </el-form-item>
          <el-form-item label="商品名" prop="name">
            <el-input v-model="addform.name" clearable placeholder="商品名"></el-input>
          </el-form-item>
         <el-form-item label="商品类别" prop="typeId">
             <!-- <el-select v-model="addform.typeId" clearable  placeholder="请选择商品类别">
               <el-option v-for="item in showType" :key="item.id" :value="item.id" :label="item.name"/>
            </el-select> -->
            <el-cascader
                 :props="{value:'id',label:'name',children:'children'}"
                 :options="showType"
                 v-model="addform.typeId"
                 :clearable="true"
                 :value-key="addform.typeId"
                 :value="showType.id"
                 :key="showType.id"
                 :show-all-levels="false"
                 filterable
                 clearable
                 @change="addhandleChange"></el-cascader>
          </el-form-item>
          <el-form-item label="零售价" prop="shou">
            <!-- <el-input-number v-model="addform.shou" controls-position="left"  @change="handleChange" :min="0" clearable placeholder="零售价" /> -->
            <el-input v-model="addform.shou" clearable placeholder="零售价"></el-input>
          </el-form-item>
          <el-form-item label="最低售价" prop="standby3">
            <el-input v-model="addform.standby3" clearable placeholder="最低售价"></el-input>
          </el-form-item>
          <el-form-item label="进货价" prop="jin">
            <el-input v-model="addform.jin" clearable placeholder="进货价"></el-input>
          </el-form-item>
          <el-form-item label="单位" prop="danWei">
            <el-input v-model="addform.danWei" clearable placeholder="单位"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="addform.remark" clearable placeholder="备注"></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="state">
           <el-select v-model="addform.state" clearable placeholder="请选择状态">
             <el-option label="上架" value="1"></el-option>
             <el-option label="下架" value="0"></el-option>
           </el-select>
          </el-form-item>
        </el-form>
    <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="pushs('addform')">提 交</el-button>
        <el-button  @click="reset('addform')">重 置</el-button>
    </div>
    </el-dialog>

    <!-- 修改-->
    <el-dialog
         title="修改商品"
         v-dialogDrag
         :close-on-click-modal="false"
         :modal="false"
         :visible.sync="updateshow">
    <el-form :model="updateform" :inline="true" class="demo-form-inline" label-width="120px">
        <el-form-item label="商品序号">
          <el-input v-model="updateform.num" clearable placeholder="商品序号"></el-input>
        </el-form-item>
        <el-form-item label="商品名">
          <el-input v-model="updateform.name" clearable placeholder="商品名"></el-input>
        </el-form-item>
        <el-form-item label="商品类别">
          <!-- <el-select v-model="updateform.typeId" clearable  placeholder="请选择商品类别">
             <el-option v-for="item in showType" :key="item.id" :value="item.id" :label="item.name"/>
          </el-select> -->
          <el-cascader
               :props="{value:'id',label:'name',children:'children'}"
               :options="showType"
               v-model="updateform.typeId"
               :clearable="true"
               :value-key="updateform.typeId"
               :value="showType.id"
               :key="showType.id"
               :show-all-levels="false"
               clearable
               @change="updhandleChange"></el-cascader>
        </el-form-item>
        <el-form-item label="零售价">
          <el-input v-model="updateform.shou" clearable placeholder="零售价"></el-input>
        </el-form-item>
        <el-form-item label="最低售价">
          <el-input v-model="updateform.standby3" clearable placeholder="零售价"></el-input>
        </el-form-item>
        <el-form-item label="进货价">
          <el-input v-model="updateform.jin" clearable placeholder="进货价"></el-input>
        </el-form-item>
        <el-form-item label="单位">
           <el-input v-model="updateform.danWei" clearable placeholder="单位"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="updateform.remark" clearable placeholder="备注"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="updateform.state" clearable placeholder="请选择状态" value-key="updateform.state">
            <el-option label="上架" :value="1" :key="1"></el-option>
            <el-option label="下架" :value="0" :key="0"></el-option>
          </el-select>
        </el-form-item>
       <el-input v-model="updateform.id" type="hidden"></el-input>
    </el-form>
    <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updatepush()">提 交</el-button>
        <el-button  @click="err()">取 消</el-button>
    </div>
    </el-dialog>

    <!-- 快速改价 -->
     <el-dialog
         title="快速改价"
         v-dialogDrag
         :close-on-click-modal="false"
         :modal="false"
         :visible.sync="updateshowgj"
         width="60%">
    <el-table :v-model="updateprice" :data="table" style="width: 100%">
    <el-table-column prop="num" label="商品序号" width="180"></el-table-column>
    <el-table-column prop="name" label="商品名称" width="180"></el-table-column>
    <el-table-column prop="shou" label="商品售价" width="180">
        <template slot-scope="scope">
          <el-input v-model="scope.row.shou" placeholder="请输入商品售价"></el-input>
        </template>
    </el-table-column>
    <el-table-column prop="standby3" label="最低售价" width="180">
        <template slot-scope="scope">
          <el-input v-model="scope.row.standby3" placeholder="请输入商品售价"></el-input>
        </template>
    </el-table-column>
    <el-table-column prop="jin" label="商品进价" width="180">
        <template slot-scope="scope">
          <el-input v-model="scope.row.jin" placeholder="请输入商品进价"></el-input>
        </template>
    </el-table-column>
    <el-table-column prop="danWei" label="商品单位" width="180"></el-table-column>
       <el-input v-model="updateprice.id" type="hidden"></el-input>
    </el-table>
    <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updatejg()">提 交</el-button>
        <el-button  @click="err()">取 消</el-button>
    </div>
    </el-dialog>


  </div>
</template>

<script>
  import {showsp,add,update,del,batchDel} from '@/api/product'
  import {showType} from '@/api/producttype'
  import {getAll} from '@/api/depot'
  export default {
      data() {
        return {
          //查询
          form: {
            name: '',
            state: '',
            typeId:''
          },
          leibie:'',//重新定义一下在form表单模糊查询时的商品类别的参数
          batchDeleteArr:[],//批量删除：当batchDeleteArr为空数组时，按钮不可点击
          value:[],//商品类别数组
          //分页
          page: 1,
          limit: 6,
          count: 4,
          tableData: [],
          multipleSelection:'',
          addshow:false,
          //添加商品参数
          addform: {
            num: '',
            name: '',
            typeId:'',
            shou: '',
            standby3: '',
            jin: '',
            danWei: '',
            remark: '',
            state: ''
          },
          addType:'',//重新定义一下在addform里的商品类别的参数
          showType:[],
          //编辑
          updateshow:false,
          updateform: {
            id: '',
           num: '',
           name: '',
           typeId: '',
           shou: '',
           standby3:'',
           jin: '',
           danWei: '',
           remark: '',
           state: ''
          },
          updType:'',//重新定义一下在update编辑方法时的商品类别的参数
          showDepot:[],
          //快速改价参数
          table:[{
            id:'',
            num:'',
            name:'',
            shou: '',
            standby3:'',
            jin: '',
            danWei: ''
          }],
          //快速改价
          updateshowgj:false,
          updateprice: {
            id: '',
           num: '',
           name: '',
           shou: '',
           standby3:'',
           jin: '',
           danWei: ''
          },

          //表单验证
          rules: {
            num: [
              { required: true, message: '请输入商品序号', trigger: 'blur' }
            ],
            name: [
              { required: true, message: '请输入商品名', trigger: 'blur' }
            ],
            typeId: [
              { required: true, message: '请选择所属类别', trigger: 'change' }
            ],
            shou: [
              { required: true, message: '请输入零售价', trigger: 'blur' }/* ,
              { type:'number', message: '售价必须为数字值'} */
            ],
            standby3: [
              { required: true, message: '请输入最低售价', trigger: 'blur' }/* ,
              { type:'number', message: '售价必须为数字值'} */
            ],
            jin: [
              { required: true, message: '请输入进货价', trigger: 'blur' }/* ,
              { type:'number', message: '售价必须为数字值'} */
            ],
            state: [
              { required: true, message: '请选择状态', trigger: 'change' }
            ]
          },
          isLimit:false,
        }
      },

    //钩子函数
      created() {
        //获取商品类别
        showType({'typeName':1}).then((res)=>{
        // 循环遍历json数据
        this.showType=this.childrens(res.data);
        });
        //获取所属仓库
        getAll({}).then((res)=>{
          this.showDepot=res.data;
        });
        this.showByLimit(1);
      },
      methods: {
        //分页查询所有
        showByLimit(val) { // 修改当前页所触发的函数
           return new Promise((resolve, reject) => {
             showsp({
               'limit': this.limit,
               'page': val,
               'name': this.form.name,
               'state': this.form.state,
               'typeId': this.leibie
               }).then(response => {
               const {data,count} = response
               this.tableData = data;
               this.table=data;//获取快速改价中的表格数据
               this.count = count;
               resolve()
             }).catch(error => {
               reject(error)
             })
           })
        },
        //循环删除级联选择器最后一个空数据
        childrens(sh){
          let childs=sh;
          for (var i = 0; i < childs.length; i++) {
            if (childs[i].children.length) {
                // children若为空数组，则将children设为undefined
                this.childrens(childs[i].children);
            }else{
              delete sh[i].children;
            }
          }
          return sh;
        },
        //当limit修改时分页查询所有
        handleSizeChange(val){
          this.limit=val;
           if(this.isLimit){
            return new Promise((resolve, reject) => {
              showsp({
              'limit': val,
              'page': 1,
              'name': this.form.name,
              'state': this.form.state,
              'typeId': this.leibie
              }).then(response => {
                const {data,count} = response
                this.tableData = data;
                this.table=data;
                this.count = count;
                resolve()
              }).catch(error => {
                reject(error)
              })
            })
          }else{
            return new Promise((resolve, reject) => {
              show({'limit': val,'page': this.page}).then(response => {
                const {data,count} = response
                this.tableData = data;
                resolve()
              }).catch(error => {
                reject(error)
              })
            })
          }
        },
        //查询表单按钮提交
        onSubmit() {
          console.log(this.leibie);
          //定义typeId.pop()
          this.isLimit=true;

          //查询商品、商品类别、商品状态
          return new Promise((resolve, reject) => {
            showsp({
              'limit': this.limit,
              'page': this.page,
              'name': this.form.name,
              'state': this.form.state,
              'typeId': this.leibie
            }).then(response => {
              const {
                data,
                count
              } = response
              this.tableData = data;
              this.table=data;
              this.count = count;
              resolve()
            }).catch(error => {
              reject(error)
            })
          })
        },
        //添加按钮事件
          adds(){
               this.addshow=true;
         },
        //取消让弹框隐藏
         err(){
               this.addshow=false;
               this.updateshow=false;
         },
         //编辑按钮事件
         updateProduct(row){
             this.updateshow=true;
             this.updateform=row;
             this.updateform.state=row.state;
         },
         //编辑快速改价事件
         updatePrice(){
           this.updateshowgj=true;
         },
         //提交添加
         pushs(formName) {
            //表单验证方法
           this.$refs[formName].validate((valid) => {
             if (valid) {
               return new Promise((resolve, reject) => {
                 add({
                   'num': this.addform.num,
                   'name': this.addform.name,
                   'typeId': this.addType,
                   'shou':this.addform.shou,
                   'standby3':this.addform.standby3,
                   'jin':this.addform.jin,
                   'danWei':this.addform.danWei,
                   'remark':this.addform.remark,
                   'state' :this.addform.state
                 }).then(response => {
                   if(response.data){
                     this.$message({
                         message: response.msg,
                         type: 'success',
                         code: 1500,
                       onClose:  () =>{
                         location.reload();
                       }
                     });
                     }else{
                       this.$message({
                           showClose: true,
                           message: response.msg,
                           type: 'error',
                           code: 1500,
                      });
                     }
                   resolve()
                 }).catch(error => {
                   reject(error)
                 })
               })
             } else {
               console.log('error submit!!');
               return false;
             }
           });

         },
         /* resetForm(formName) {
           this.$refs[formName].resetFields();
          }, */
         //提交修改
         updatepush() {
           return new Promise((resolve, reject) => {
             update({
               'id':this.updateform.id,
               'num':this.updateform.num,
               'name':this.updateform.name,
               'typeId':this.updType,
               'shou':this.updateform.shou,
               'standby3':this.updateform.standby3,
               'jin':this.updateform.jin,
               'danWei':this.updateform.danWei,
               'remark':this.updateform.remark,
               'state' :this.updateform.state
             }).then(response => {
               console.log(response);
               if(response.data){
                 this.$message({
                     message: response.msg,
                     type: 'success',
                     code: 1000,
                   onClose:  () =>{
                     location.reload();
                   }
                 });
                 }else{
                   this.$message({
                       showClose: true,
                       message: response.msg,
                       type: 'error'
                  });
                 }
               resolve()
             }).catch(error => {
               reject(error)
             })
           })
         },

         //提交快速改价
         updatejg() {
            let rs=true;
            let that = this;
             this.table.forEach(function(el) {
            return new Promise((resolve, reject) => {
              update({
                'id':el.id,
                'num':el.num,
                'name':el.name,
                'shou':el.shou,
                'standby3':el.standby3,
                'jin':el.jin,
                'danWei':el.danWei
              }).then(response => {
                console.log(response);
                if(!response.data){
                  rs=false
                }
                resolve()
              }).catch(error => {
                reject(error)
              })
            })
           })
          if(rs){
          that.$message({
              showClose: true,
              message: '操作成功',
              type: 'success',
              onClose: ()=>{
               /* location.reload(); */

              }
            });
          }
          },
          //表单模糊查询时
          handleChange(value){
            console.log(value);
            this.leibie=value[value.length-1];
            console.log(this.leibie);
          },
          //添加时
          addhandleChange(value){
            console.log(value);
            this.addType=value[value.length-1];
            console.log(this.addType);
          },
          //编辑时
          updhandleChange(value){
            console.log(value);
            this.updType=value[value.length-1];
            console.log(this.updType);
          },

         //删除
         delProduct(row) {
           this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
                           confirmButtonText: '确定',
                           cancelButtonText: '取消',
                           type: 'warning'
                       }).then(response => {
              return new Promise((resolve, reject) => {
                del({'id': row.id}).then(response => {
                 if(response.data){
                   this.$message({
                     message: response.msg,
                     type: 'success',
                     code: 1500,
                     onClose:  () =>{
                       location.reload();
                     }
                   });
                 }else{
                    this.$message.error(response.msg);
                 }
                  resolve()
                }).catch(error => {
                  reject(error)
                })
              })
               resolve()
             }).catch(error => {
               reject(error)
             })
         },
         /* 批量删除*/
         handleSelectionChange(val) {
          this.batchDeleteArr = val //在change事件动态获取batchDeleteArr 
          //循环遍历获取要批量删除的数据
           let a="";
           for(let i=0;i<val.length;i++){
             a+=val[i].id+","
           }
          this.multipleSelection =a;
           //console.log(this.multipleSelection);
         },

         //批量删除
         batchList(){
           this.$confirm('此操作将永久删除所选商品, 是否继续?', '提示', {
             confirmButtonText: '确定',
             cancelButtonText: '取消',
             type: 'warning'
           }).then(() => {
             return new Promise((resolve, reject) => {
               batchDel(this.multipleSelection).then(response => {
                 resolve();
                 this.$message({
                   type: 'success',
                   message: '删除成功!',
                   onClose: () => {
                     location.reload()
                   }
                 });
               }).catch(error => {
                 this.$message({
                   type: 'error',
                   message: '删除失败'
                 });
                 reject(error)
               })
             })
           })

         },

        clearFilter() {
          this.$refs.filterTable.clearFilter();
        },

        filterTag(value, row) {
          return row.state === value;
        },

        //添加重置
        reset(addform) {
           this.$refs[addform].resetFields();
         },
      }
    }
</script>
